//
//  ViewController.m
//  Socket-Client-Study
//
//  Created by SWRD on 3/12/14.
//  Copyright (c) 2014 ronghai_fan. All rights reserved.
//

#import "ViewController.h"
#import "AsyncSocket.h"

@interface ViewController () <UITextFieldDelegate, AsyncSocketDelegate, UIScrollViewDelegate> {
    
    AsyncSocket *_socket;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    _clientIPAddress.text = @"****";
    _clientPort.text = @"8080";
	_clientIPAddress.delegate = self;
    _receiveData.editable = NO;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    return YES;
}

- (void)append:(NSString *)text {
    
    _receiveData.text = [_receiveData.text stringByAppendingFormat:@"%@\n", text];
}

- (IBAction)Send:(id)sender {
    // 判断发送数据不为空，客户端IP不为空，端口不为空
    if (!(_sendMessage.text.length == 0) && !(_clientIPAddress.text.length == 0) && !(_clientPort.text.length == 0)) {
        
        // Socket
        if (_socket == nil) {
            _socket = [[AsyncSocket alloc] init];
        }
        
        // 发送数据到Socket，发送完成会调用代理方法
        [_socket writeData:[_sendMessage.text dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
        // 输入框取消第一响应者
        [_sendMessage resignFirstResponder];
        // 拼接
        [self append:[NSString stringWithFormat:@"Me:%@", _sendMessage.text]];
        // 从Socket读取第一个可用数据，如果timeout的值为负数，则读取操作不会存在超时
        [_socket readDataWithTimeout:-1 tag:0];
    } else {
        // 弹出警告信息
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Warning!"
                              message:@"Please Input Message/ClientIP/ClientPort"
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil, nil];
        
        [alert show];
    }
}

// 重复发送
- (IBAction)repeats:(id)sender {
    NSTimeInterval timeInterval = 1.0;
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(Send:) userInfo:nil repeats:YES];
    [timer fire];
}

// 连接到服务器
- (IBAction)connectToServer:(id)sender {
    
    if (_socket == nil) {
        // 初始化Socket
        _socket = [[AsyncSocket alloc] initWithDelegate:self];
        NSError *error = nil;
        
        // 连接到主机
        if (![_socket connectToHost:_clientIPAddress.text onPort:[_clientPort.text intValue] error:&error]) {
            // 连接失败
            _status.text = @"Could't Connect Server";
        } else {
            // 连接成功
            _status.text = @"Connect Server Successfully";
        }
    } else {
        // 已经连接成功
        _status.text = @"Connect Server Successfully";
    }
}

#pragma mark AsyncSocket Delegate

// 建立连接
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
    
    [self append:[NSString stringWithFormat:@"ConnectToHost:%@", host]];
    [sock readDataWithTimeout:-1 tag:0];
}

// Socket完成写入请求数据后调用
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag {
    
    [sock readDataWithTimeout:-1 tag:0];
}

// 读取数据
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    
    NSString *newMessage = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    [self append:[NSString stringWithFormat:@"%@:%@", sock.connectedHost, newMessage]];
    [_socket readDataWithTimeout:-1 tag:0];//可以省略
}

// 是否加密
- (void)onSocketDidSecure:(AsyncSocket *)sock {
    NSLog(@"onSocket:%p", sock);
    
}

// 遇到错误时断开连接
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err {
    [self append:[NSString stringWithFormat:@"onSocket:%p, error:%@", sock, err.localizedDescription]];
}

// 断开连接
- (void)onSocketDidDisconnect:(AsyncSocket *)sock {
    NSString *msg = @"Connect is disconnect";
    _status.text = msg;
    _socket = nil;
}

@end
